package com.business.frame.action;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.business.base.BaseController;
import com.business.base.Pager;
import com.business.frame.po.FieldBean;
import com.business.frame.service.FieldService;
import com.business.frame.service.TableService;
import com.business.frame.service.TypeService;
import com.common.ErrorLog;
import com.common.NumberProcess;
import com.common.RenderPage;
import com.common.StringProcess;
import com.common.utils.SpringContextHolder;

@Controller
@RequestMapping(value = "/frame/field")
public class FieldController {

	@Autowired
	private FieldService fieldService;

	@Autowired
	private TableService tableService;

	@Autowired
	private TypeService typeService;
	
	private List<Map<String, Object>> tableList;

	@RequestMapping({ "/list" })
	public String list(HttpServletRequest request, ModelMap model) {

		try {
			String tableId = StringProcess.getRequest(request.getParameter("tableId"), "");
			if (tableId.length() > 0) {
				model.put("urlParam", "?tableId=" + tableId);
			}
		} catch (Exception e) {
			ErrorLog.OnWrite(e);
		}

		return "frame/field/list";
	}

	@RequestMapping({ "/detail" })
	public String detail(HttpServletRequest request, ModelMap model) {

		try {
			String fieldId = StringProcess.getRequest(request.getParameter("fieldId"), "");

			// 初始化控件
			// 表格下拉
			Map<String, Object> searchTable = new HashMap<String, Object>();
			searchTable.put("columns", "TableId,TableName");
			tableList = tableService.select(searchTable);

			// 类型下拉
			List<Map<String, Object>> typeList = new ArrayList<Map<String, Object>>();
			Map<String, Object> typeItem = new HashMap<String, Object>();
			typeItem.put("code", "number");
			typeItem.put("text", "数字");
			typeList.add(typeItem);
			typeItem = new HashMap<String, Object>();
			typeItem.put("code", "decimal");
			typeItem.put("text", "小数");
			typeList.add(typeItem);
			typeItem = new HashMap<String, Object>();
			typeItem.put("code", "string");
			typeItem.put("text", "字符");
			typeList.add(typeItem);
			typeItem = new HashMap<String, Object>();
			typeItem.put("code", "text");
			typeItem.put("text", "内容");
			typeList.add(typeItem);
			typeItem = new HashMap<String, Object>();
			typeItem.put("code", "datetime");
			typeItem.put("text", "日期");
			typeList.add(typeItem);
			typeItem = new HashMap<String, Object>();
			typeItem.put("code", "file");
			typeItem.put("text", "文件");
			typeList.add(typeItem);

			// 已经使用类型
			Map<String, Object> searchUseType = new HashMap<String, Object>();
			searchUseType.put("isEnable", "1");
			List<Map<String, Object>> useTypeList = typeService.select(searchUseType);
			for (int i = 0; i < useTypeList.size(); i++) {
				Map<String, Object> useTypeItem = useTypeList.get(i);

				String typeId = StringProcess.convertToString(useTypeItem.get("TypeId"));
				String fieldType = StringProcess.convertToString(useTypeItem.get("FieldType"));
				int fieldLength = NumberProcess.convertToNumber(useTypeItem.get("FieldLength"));
				int isKey = NumberProcess.convertToNumber(useTypeItem.get("IsKey"));
				int isAllowNull = NumberProcess.convertToNumber(useTypeItem.get("IsAllowNull"));

				String value1 = "[" + fieldType + "]";
				String value2 = "";
				if (fieldLength > 0) {
					value2 = "[长度：" + fieldLength + "]";
				}
				String value3 = "";
				if (isKey > 0) {
					value3 = "[主键]";
				}
				String value4 = "";
				if (isAllowNull > 0) {
					value4 = "[允许为空]";
				} else {
					value4 = "[允许为空]";
				}

				useTypeItem.put("code", typeId);
				useTypeItem.put("text", value1 + value2 + value3 + value4);
			}

			String action = "";
			FieldBean bean = new FieldBean();
			if (fieldId.length() == 0) {
				action = "insert";
				fieldId = StringProcess.getUUID();
				bean.setFieldId(fieldId);

			} else {
				action = "update";
				bean = fieldService.getBeanByKeyId(fieldId);
			}

			model.put("action", action);
			model.put("tableList", tableList);
			model.put("typeList", typeList);
			model.put("useTypeList", useTypeList);
			model.put("bean", bean);

		} catch (Exception e) {
			ErrorLog.OnWrite(e);
		}

		return "frame/field/detail";
	}

	@RequestMapping("/query")
	public void query(Integer pageIndex, Integer pageSize, HttpServletRequest request, HttpServletResponse response,
			ModelMap map) {

		try {
			Map<String, Object> search = new HashMap<String, Object>();

			// URL查询
			String tableId = StringProcess.getRequest(request.getParameter("tableId"), "");
			if (tableId.length() > 0) {
				search.put("tableId", tableId);
			}
			// URL查询

			// 页面查询
			String fieldName = request.getParameter("txtFieldName");
			if (fieldName != null) {
				fieldName = fieldName.trim();
				if (fieldName.length() > 0) {
					search.put("fieldName", "%" + fieldName + "%");
				}
			}
			// 页面查询

			Pager<Map<String, Object>> result = fieldService.selectPage(pageIndex, pageSize, search);

			int resultCount = result.getList().size();
			for (int i = 0; i < resultCount; i++) {
				Map<String, Object> item = result.getList().get(i);
				
				item = BaseController.AddChangeRow(SpringContextHolder.getBean(FieldService.class), result.getList(), item, result.getTotal(), pageIndex, i, result.getPages(), pageSize, resultCount,"FieldId","OrderNumber", search);
			}
			
			RenderPage.JsonByObject(response, result);

		} catch (Exception e) {
			ErrorLog.OnWrite(e);
		}
	}
	

	@RequestMapping(params = "method=delete", method = RequestMethod.POST)
	public void del(HttpServletRequest request, HttpServletResponse response, String selectitem) {
		// TODO Auto-generated method stub

		try {
			String[] fieldIdArray = selectitem.split(",");

			for (String fieldId : fieldIdArray) {
				if (fieldId.length() > 0) {
					fieldService.delete(fieldId);
				}
			}

			RenderPage.JsonByString(response, "1");
		} catch (Exception e) {
			ErrorLog.OnWrite(e);
		}

	}

	@RequestMapping(params = "method=save", method = RequestMethod.POST)
	public void save(HttpServletRequest request, HttpServletResponse response, String action) {

		try {
			String fieldId = request.getParameter("txtFieldId");
			String tableId = request.getParameter("lstTableName");
			
			String tableName="";
			for(int i=0;i<tableList.size();i++)
			{
				if(StringProcess.convertToString(tableList.get(i).get("TableId")).equals(tableId))
				{
					tableName=StringProcess.convertToString(tableList.get(i).get("TableName"));
				}
			}
			
			String fieldName = request.getParameter("txtFieldName");
			String fieldText = request.getParameter("txtFieldText");
			String typeId = request.getParameter("lstType");
			String isKey = request.getParameter("chkIsKey");
			if(!"1".equals(isKey))
			{
				isKey="0";
			}
			String isAllowNull = request.getParameter("chkIsAllowNull");
			if(!"1".equals(isAllowNull))
			{
				isAllowNull="0";
			}
			String fieldType = request.getParameter("lstFieldType");
			String fieldLength = request.getParameter("txtFieldLength");
			String wordWhite = request.getParameter("txtWordWhite");
			String wordBlack = request.getParameter("txtWordBlack");
			String fieldBackupName="";
			String fieldRegex = request.getParameter("txtFieldRegex");
			String orderNumber = request.getParameter("txtOrderNumber");

			Map<String, Object> model = new HashMap<String, Object>();
			model.put("fieldId", fieldId);
			model.put("tableId", tableId);
			model.put("tableName", tableName);
			model.put("fieldName", fieldName);
			model.put("fieldText", fieldText);
			model.put("typeId", typeId);
			model.put("isKey", isKey);
			model.put("isAllowNull", isAllowNull);
			model.put("fieldType", fieldType);
			model.put("fieldLength", fieldLength);
			model.put("wordWhite", wordWhite);
			model.put("wordBlack", wordBlack);
			model.put("fieldBackupName", fieldBackupName);
			model.put("fieldRegex", fieldRegex);
			model.put("orderNumber", orderNumber);

			if (action.equals("insert")) {
				fieldService.insert(model);
			} else if (action.equals("update")) {
				fieldService.update(model);
			}

			RenderPage.JsonByString(response, "1");
		} catch (Exception e) {
			ErrorLog.OnWrite(e);
		}

	}

}
